package no.ntnu.fp.gui.listeners;

import java.io.IOException;

import no.ntnu.fp.client.Client;
import no.ntnu.fp.client.exceptions.NetworkException;
import no.ntnu.fp.gui.events.LoginRequestedEvent;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.services.EmployeeService;

public class LoginListener implements GuiListener<LoginRequestedEvent> {
	
	private final EmployeeService employeeService;
	private final Connection connection;
	
	public LoginListener(Connection connection, 
			EmployeeService employeeService) {
		this.employeeService = employeeService;
		this.connection = connection;
	}
	

	@Override
	public void handleEvent(LoginRequestedEvent evt) {
		try {
			connection.connect(Client.getServerAddress(), Client.getServerPort());
			System.out.println("Connected");
		} catch (IOException ex) { 
			throw new NetworkException("Unable to connect to server", ex);
		}
		
		Client.startReceiveWorker(connection);
		
		try {
			employeeService.logInEmployeeByCredentials(evt.getUsername(), evt.getPassword());
			System.out.println("Package sent");
		} catch (IOException ex) {
			throw new NetworkException("Unable to send login request to server", ex);
		}
	}


	@Override
	public boolean isLongRunningListener() {
		return true;
	}

}
	